package com.example.aussiehealthhelper;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;

public class DrugNameSearchActivity extends AppCompatActivity {

    private EditText etSearch;
    private DrugAdapter adapter;
    private HealthDbHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drug_name_search);
        dbHelper = new HealthDbHelper(this);
        etSearch = findViewById(R.id.etSearch);
        RecyclerView rvResults = findViewById(R.id.rvResults);
        rvResults.setLayoutManager(new LinearLayoutManager(this));
        adapter = new DrugAdapter(new ArrayList<>(), new DrugAdapter.DrugClickListener() {
            @Override
            public void onDrugClick(Drug drug) {
                //跳转到药品详情
                showDrugDetail(drug);
            }
        });

        rvResults.setAdapter(adapter);

        //搜索按钮
        Button btnSearch = findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(v -> performSearch());

        //在启动时显示所有药品
        performSearch();

        //添加文本变化监听器
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //用户清空搜索框时自动显示所有药品
                if (s.toString().trim().isEmpty()) {
                    performSearch();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

    private void performSearch() {
        String keyword = etSearch.getText().toString().trim();
        new SearchTask().execute(keyword);
    }

    private class SearchTask extends AsyncTask<String, Void, List<Drug>> {
        @Override
        protected List<Drug> doInBackground(String... keywords) {
            String keyword = keywords[0];
            List<Drug> results = new ArrayList<>();
            SQLiteDatabase db = dbHelper.getReadableDatabase();

            String query;
            String[] selectionArgs;

            if (keyword.isEmpty()) {
                //没有搜索词时查询所有药品
                query = "SELECT * FROM " + HealthDbHelper.TABLE_DRUGS;
                selectionArgs = null;
            } else {
                //有搜索词时执行关键词搜索
                query = "SELECT * FROM " + HealthDbHelper.TABLE_DRUGS +
                        " WHERE " + HealthDbHelper.COLUMN_NAME_CN + " LIKE ? OR " +
                        HealthDbHelper.COLUMN_NAME_EN + " LIKE ?";

                selectionArgs = new String[]{
                        "%" + keyword + "%",
                        "%" + keyword + "%"
                };
            }

            try (Cursor cursor = db.rawQuery(query, selectionArgs)) {
                int idIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_DRUG_ID);
                int cnIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_NAME_CN);
                int enIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_NAME_EN);
                int indicationIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_INDICATION);
                int categoryIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_INDICATION_CATEGORY);
                int adverseIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_ADVERSE);
                int similarIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_SIMILAR);
                int dosageIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_DOSAGE);
                int noteIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_NOTE);
                int favoriteIndex = cursor.getColumnIndex(HealthDbHelper.COLUMN_IS_FAVORITE);

                while (cursor.moveToNext()) {
                    // 确保所有列索引有效
                    int id = idIndex != -1 ? cursor.getInt(idIndex) : -1;
                    String cnName = cnIndex != -1 ? cursor.getString(cnIndex) : "";
                    String enName = enIndex != -1 ? cursor.getString(enIndex) : "";
                    String indication = indicationIndex != -1 ? cursor.getString(indicationIndex) : "";
                    String category = categoryIndex != -1 ? cursor.getString(categoryIndex) : "";
                    String adverse = adverseIndex != -1 ? cursor.getString(adverseIndex) : "";
                    String similar = similarIndex != -1 ? cursor.getString(similarIndex) : "";
                    String dosage = dosageIndex != -1 ? cursor.getString(dosageIndex) : "";
                    String note = noteIndex != -1 ? cursor.getString(noteIndex) : "";

                    //处理收藏字段
                    boolean isFavorite = false;
                    if (favoriteIndex != -1) {
                        int favoriteValue = cursor.getInt(favoriteIndex);
                        isFavorite = (favoriteValue == 1);
                    }

                    //Drug构造函数
                    Drug drug = new Drug(
                            id,
                            cnName,
                            enName,
                            indication,
                            category,
                            adverse,
                            similar,
                            dosage,
                            note,
                            isFavorite
                    );
                    results.add(drug);
                }
            }
            return results;
        }

        @Override
        protected void onPostExecute(List<Drug> results) {
            adapter.updateData(results);
        }
    }

    private void showDrugDetail(Drug drug) {
        Intent intent = new Intent(this, DrugDetailActivity.class);
        intent.putExtra("DRUG_ID", drug.getId());
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        if (dbHelper != null) {
            dbHelper.close();
        }
        super.onDestroy();
    }
}